package com.apkcore.core

import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import androidx.lifecycle.asLiveData
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.MutableSharedFlow
import java.util.concurrent.ConcurrentHashMap

object FlowBusX {
    private var events = ConcurrentHashMap<Any, MutableSharedFlow<Any>>()
    private var stickyEvents = ConcurrentHashMap<Any, MutableSharedFlow<Any>>()

    private fun <T> with(objectKey: Any): MutableSharedFlow<T> {
        return events.getOrPut(objectKey) {
            MutableSharedFlow(
                0,
                1,
                BufferOverflow.DROP_OLDEST
            )
        } as MutableSharedFlow<T>
//        if (!events.containsKey(objectKey)) {
//            events[objectKey] = MutableSharedFlow(0, 1, BufferOverflow.DROP_OLDEST)
//        }
//        return events[objectKey] as MutableSharedFlow<T>
    }

    private fun <T> withSticky(objectKey: Any): MutableSharedFlow<T> {
        return stickyEvents.getOrPut(objectKey) {
            MutableSharedFlow(
                1,
                1,
                BufferOverflow.DROP_OLDEST
            )
        } as MutableSharedFlow<T>
//        if (!stickyEvents.containsKey(objectKey)) {
//            stickyEvents[objectKey] = MutableSharedFlow(1, 1, BufferOverflow.DROP_OLDEST)
//        }
//        return stickyEvents[objectKey] as MutableSharedFlow<T>
    }

    fun <T> observe(owner: LifecycleOwner, objectKey: Any, observer: Observer<T>) {
        return with<T>(objectKey).asLiveData().observe(owner, observer)
    }

    fun <T> observeForever(objectKey: Any, observer: Observer<T>) {
        return with<T>(objectKey).asLiveData().observeForever(observer)
    }


    fun <T> observeSticky(owner: LifecycleOwner, objectKey: Any, observer: Observer<T>) {
        return withSticky<T>(objectKey).asLiveData().observe(owner, observer)
    }

    fun <T> observerStickyForever(objectKey: Any, observer: Observer<T>) {
        return withSticky<T>(objectKey).asLiveData().observeForever(observer)
    }

    fun <T> post(objectKey: Any, objectValue: T) {
        with<T>(objectKey).tryEmit(objectValue)
    }

    fun <T> postSticky(objectKey: Any, objectValue: T) {
        withSticky<T>(objectKey).tryEmit(objectValue)
    }
}
